'use client'

import { zodResolver } from '@hookform/resolvers/zod'
import {
	Button,
	Card,
	CardActions,
	CardContent,
	CircularProgress,
	Skeleton,
	Typography
} from '@mui/material'
import Grid from '@mui/material/Unstable_Grid2'
import { useMutation, useQueryClient } from '@tanstack/react-query'
import {
	Eraser,
	Pencil,
	Save,
	Trash,
	UserRoundCog,
	UserRoundPlus
} from 'lucide-react'
import { useRouter } from 'next/navigation'
import { useCallback, useEffect, useState } from 'react'
import { useForm } from 'react-hook-form'
import { toast } from 'sonner'

import { CopyButton } from '@/components/CopyButton'
import { ConfirmationDialog } from '@/components/dialogs/confirmation.dialog'
import { TextFieldControlled } from '@/components/forms/TextFieldControlled'

import {
	type IClient,
	type IClientForm,
	clientFormScheme
} from '@/types/client.types'

import { DASHBOARD_PAGES } from '@/config/pages-url.config'

import { clientService } from '@/services/clients.service'

export function ClientCard({
	client_data,
	createMode
}: {
	client_data: IClient | undefined
	createMode?: boolean
}) {
	const queryClient = useQueryClient()
	const router = useRouter()

	const [client, setClient] = useState<IClient | undefined>(client_data)
	const [editMode, setEditMode] = useState<boolean>(createMode ?? false)
	const [showDeleteConfDialog, setShowDeleteConfDialog] =
		useState<boolean>(false)

	const {
		formState: { isDirty, isValid },
		handleSubmit,
		reset,
		control
	} = useForm<IClientForm>({
		mode: 'onChange',
		resolver: zodResolver(clientFormScheme),
		defaultValues: client
	})

	useEffect(() => {
		setClient(client_data)
		reset(client_data)
	}, [client_data])

	const updateClient = useMutation({
		mutationKey: ['client', 'update', client?.id],
		mutationFn: (data: IClientForm) => clientService.update(client?.id!, data),
		onSuccess: data => {
			setEditMode(false)
			setClient(data)
			queryClient.setQueryData(['client', data.id], data)
			queryClient.invalidateQueries({ queryKey: ['clients'] })
			toast.success('Изменения сохранены')
		},
		onError: error => {
			toast.error('Ошибка сохранения')
			console.error(error)
		}
	})

	const createClient = useMutation({
		mutationKey: ['client', 'create'],
		mutationFn: (data: IClientForm) => clientService.create(data),
		onSuccess: data => {
			setClient(data)
			reset({ ...data })
			queryClient.invalidateQueries({ queryKey: ['clients'] })
			queryClient.setQueryData(['client', data.id], data)

			router.push(`${DASHBOARD_PAGES.CLIENT}${data.id}`)

			toast.success(`Клиент создан`, {
				description: `${data.first_name} ${data.last_name} #${data.id}`
			})
		},
		onError: () => {
			toast.error('Ошибка создания')
		}
	})

	const deleteClient = useMutation({
		mutationKey: ['client', 'delete', client?.id],
		mutationFn: () => clientService.del(client?.id!),
		onSuccess: () => {
			queryClient.invalidateQueries({
				queryKey: ['client', client?.id]
			})
			queryClient.invalidateQueries({ queryKey: ['clients'] })

			router.back()
			toast.success('Клиент удален', {
				description: `${client?.first_name} ${client?.last_name} #${client?.id}`
			})
		}
	})

	const isPending =
		updateClient.isPending || deleteClient.isPending || createClient.isPending

	const enableEditMode = useCallback(
		() => !createMode && setEditMode(true),
		[createMode]
	)
	const declineEditMode = useCallback(() => {
		if (!createMode) setEditMode(false)
		reset(client)
	}, [client])

	const handleDelete = useCallback(() => {
		deleteClient.mutate()
	}, [deleteClient])

	const onSubmit = useCallback(
		(data: IClientForm) =>
			createMode ? createClient.mutate(data) : updateClient.mutate(data),
		[createMode, createClient, updateClient]
	)

	return (
		<Card>
			<form noValidate>
				<CardContent>
					{!createMode && (
						<Typography
							sx={{ fontSize: 14 }}
							color='text.secondary'
							gutterBottom
						>
							{client ? (
								<>
									Идентификатор в системе #{client.id}
									<CopyButton
										text={client.id.toString()}
										size={14}
									/>
								</>
							) : (
								<Skeleton />
							)}
						</Typography>
					)}
					<Typography
						variant='h5'
						component='div'
					>
						{client ? (
							!createMode ? (
								<>
									{client.first_name} {client.last_name}
									<CopyButton
										text={`${client.first_name} ${client.last_name}`}
										size={14}
									/>
								</>
							) : (
								'Новый клиент'
							)
						) : (
							<Skeleton />
						)}
					</Typography>
					{!createMode && (
						<Typography
							sx={{ mb: 1.5, display: 'flex' }}
							color='text.secondary'
						>
							<UserRoundPlus
								size={18}
								style={{ marginRight: 4 }}
							/>
							{client ? (
								client.created_on.format('HH:mm DD.MM.YYYY')
							) : (
								<Skeleton width={60} />
							)}
							;
							<UserRoundCog
								size={18}
								style={{ marginRight: 4, marginLeft: 4 }}
							/>
							{client ? (
								client.updated_on.format('HH:mm DD.MM.YYYY')
							) : (
								<Skeleton width={60} />
							)}
						</Typography>
					)}
					{client ? (
						<Grid
							container
							spacing={3}
						>
							<Grid xs={'auto'}>
								<TextFieldControlled
									control={control}
									name='first_name'
									label='Имя'
									onDoubleClick={enableEditMode}
								/>
							</Grid>

							<Grid xs={'auto'}>
								<TextFieldControlled
									control={control}
									name='last_name'
									label='Фамилия'
									onDoubleClick={enableEditMode}
								/>
							</Grid>

							<Grid xs={'auto'}>
								<TextFieldControlled
									control={control}
									name='phone_number'
									label='Телефон'
									type='tel'
									copyBtn={true}
									onDoubleClick={enableEditMode}
								/>
							</Grid>

							<Grid xs={'auto'}>
								<TextFieldControlled
									control={control}
									name='email'
									label='Почта'
									type='email'
									copyBtn={true}
									onDoubleClick={enableEditMode}
								/>
							</Grid>

							<Grid xs={12}>
								<TextFieldControlled
									control={control}
									name='note'
									label='Заметка'
									onDoubleClick={enableEditMode}
									multiline
								/>
							</Grid>
						</Grid>
					) : (
						<Skeleton
							variant='rectangular'
							height={300}
						/>
					)}
				</CardContent>
				<CardActions>
					{client && !createMode && (
						<ConfirmationDialog
							open={showDeleteConfDialog}
							title={'Вы уверены, что хотите УДАЛИТЬ этого КЛИЕНТА?'}
							onConfirm={handleDelete}
							onClose={() => setShowDeleteConfDialog(false)}
						/>
					)}
					{client && !editMode && !createMode && (
						<>
							<Button
								size='small'
								startIcon={<Pencil size={20} />}
								onClick={enableEditMode}
							>
								Редактировать
							</Button>
							<Button
								size='small'
								color={'error'}
								startIcon={<Trash size={20} />}
								onClick={() => setShowDeleteConfDialog(true)}
								disabled={isPending}
							>
								Удалить
							</Button>
						</>
					)}
					{editMode && (
						<Button
							size='small'
							color={'success'}
							startIcon={<Save size={20} />}
							onClick={handleSubmit(onSubmit)}
							disabled={isPending || !isDirty || !isValid}
						>
							Сохранить
						</Button>
					)}
					{editMode && (
						<Button
							size='small'
							color={'error'}
							startIcon={<Eraser size={20} />}
							onClick={declineEditMode}
							disabled={isPending}
						>
							{createMode ? 'Очистить' : 'Отменить'}
						</Button>
					)}
					{editMode && isPending && <CircularProgress size={20} />}
				</CardActions>
			</form>
		</Card>
	)
}
